<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ page import="java.io.File"%>
<%@ page import="java.util.Iterator"%>
<%@ page import="java.util.List"%>
<%@ page import="java.net.*" %>
<%@ page import="org.apache.commons.fileupload.*"%>
<%@ page import="org.apache.commons.fileupload.disk.DiskFileItemFactory"%>
<%@ page import="org.apache.commons.fileupload.servlet.ServletFileUpload"%>
<%@ page import="org.apache.commons.io.FilenameUtils"%>
<%--
FileUpload jar download version and link
http://commons.apache.org/proper/commons-fileupload/download_fileupload.cgi
Commons FileUpload 1.3

IO jar download version and link
http://commons.apache.org/proper/commons-io/download_io.cgi
Commons IO 2.4 (requires JDK 1.6+)
 --%>    
<%
    int yourMaxMemorySize = 1024 * 1024 * 1024;
	File yourTempDirectory = new File("/tmp");
	int yourMaxRequestSize = 100 * 1024 * 1024;
	boolean writeToFile = true;
	String allowedFileTypes = ".txt .pdf .doc .ppt .xls .csv .dbf .gif .jpg .jpeg .png .swf .htm .html .zip .rar";

	String saveDirectory = application.getRealPath("/upload");
	
	//if(!uploadedFile.exists())uploadedFile.mkdir();
	File dir=new File(saveDirectory);
	if(!dir.exists())dir.mkdir();
	
	
	// Check that we have a file upload request
	boolean isMultipart = ServletFileUpload.isMultipartContent(request);
	out.println("isMultipart=" + isMultipart + "<br>");

	// Create a factory for disk-based file items
	DiskFileItemFactory factory = new DiskFileItemFactory(yourMaxMemorySize, yourTempDirectory);
	
	// Create a new file upload handler
	ServletFileUpload upload = new ServletFileUpload(factory);

	// Set overall request size constraint
	upload.setSizeMax(yourMaxRequestSize);

	//Create a progress listener
	ProgressListener progressListener = new ProgressListener() {
		private long megaBytes = -1;

		public void update(long pBytesRead, long pContentLength, int pItems) {
			long mBytes = pBytesRead / 1000000;
			if (megaBytes == mBytes) {
				return;
			}
			megaBytes = mBytes;
			System.out.println("We are currently reading item "	+ pItems);
			if (pContentLength == -1) {
				System.out.println("So far, " + pBytesRead	+ " bytes have been read.");
			} else {
				System.out.println("So far, " + pBytesRead + " of "	+ pContentLength + " bytes have been read.");
			}
		}
	};
	upload.setProgressListener(progressListener);
	upload.setHeaderEncoding("utf-8");
	try {
		// Parse the request
		List /* FileItem */items = upload.parseRequest(request);
		String fileN = "";
		// Process the uploaded items
		Iterator iter = items.iterator();
		while (iter.hasNext()) {
			FileItem item = (FileItem) iter.next();

			if (item.isFormField()) {	
				String name = item.getFieldName();
				
				String value = item.getString("UTF-8");
				out.println(name + "=" + value + "<br />");
				out.print("FileName="+name);
			} else {
				String fileName = item.getName();
				fileN = fileName;
				if (fileName != null && !"".equals(fileName)) {
					if (writeToFile) {
						fileName = FilenameUtils.getName(fileName);
						out.println("fileName to be saved=" + fileName + "<br />");
						String extension = FilenameUtils.getExtension(fileName);
						if (allowedFileTypes.indexOf(extension.toLowerCase()) != -1) {
						    File uploadedFile = new File(saveDirectory,	fileName);	
						    	
						    	
						    item.write(uploadedFile);
						} else {
							out.println("Upload File can not be " + extension + "<br />");
						}
					} else {
						byte[] data = item.get();
						out.println("data size=" + data.length + "<br />");
					}
				}
			}
		}
		
		out.println("上傳成功：upload/"+fileN);
		
		
		//上傳好檔案，把檔名傳去createAccGroupSql.jsp，讀xls
		String url = "createAccGroupSql.jsp?filename=" + URLEncoder.encode(fileN,"UTF-8");
		out.println(url);
		response.sendRedirect(url);
				
		
	} catch (FileUploadBase.SizeLimitExceededException ex1) {
		out.println("File out off size" + yourMaxRequestSize / (1024 * 1024) + "MB !");
	}
%>

